<template>
	<div>
		<Card :bstocked="false" dis-hover class="mt15">
			<Form ref="stockData" :model="stockData" :label-width="labelWidth" :label-position="labelPosition"
				class="tabform" @submit.native.prevent>
				<div class="acea-row">
					<FormItem :label="$t('page.stock.date')+'：'">
						<DatePicker :editable="false" :clearable="true" @on-change="onchangeTime" :value="timeVal"
							format="yyyy/MM/dd" type="datetimerange" placement="bottom-start"
							:placeholder="$t('page.stock.date')" style="width: 250px" class="mr30">
						</DatePicker>
					</FormItem>
					<FormItem :label="$t('page.stock.name')+'：'">
						<Input v-model="stockData.sku" :placeholder="$t('page.stock.search_product')" element-id="name"
							clearable style="width:250px;">
						</Input>
					</FormItem>
					<FormItem :label="$t('page.stock.warehouse')+'：'">
						<Select v-model="stockData.warehouse_name" clearable style="width:200px;">
							<Option v-for="item in stockNameList" :value="item.value" :key="item.value">{{ item.label }}
							</Option>
						</Select>
					</FormItem>
					<FormItem :label="$t('page.stock.stock')+'：'">
						<Select v-model="stockData.stock_type" clearable style="width:200px;">
							<Option v-for="item in stockSkuList" :value="item.value" :key="item.value">{{ item.label }}
							</Option>
						</Select>
					</FormItem>
					<FormItem label="供应商：" prop="pid" label-for="pid">
						<Select v-model="stockData.code" clearable class="input-add" filterable>
							<Option v-for="item in supplierList" :value="item.code" :key="item.code">{{item.code}}--{{ item.supplier_name }}</Option>
						</Select>
					</FormItem>
					<Button type="primary" @click="userSearchs" class="ml20">{{$t('page.stock.search')}}</Button>
					<Button @click="reset" class="ml20">{{$t('page.stock.reset')}}</Button>
					<Button type="primary" @click="exportStock" class="ml20">{{$t('page.stock.export')}}</Button>
				</div>
			</Form>
		</Card>
		<Card :bordered="false" dis-hover class="mt15">
			<div class="product_tabs tabbox">
				<Tabs v-model="stockData.tab_type" @on-click="onClickTab">
					<TabPane key="1" :label="$t('page.stock.stock')" aria-checked="true" />
					<TabPane key="2" :label="$t('page.stock.stock_change_log')" />
				</Tabs>
			</div>
			<div class="acea-row row-between">
				<div>
					<!--          <Button class="mr10" @click="queuemModal">批量发货记录</Button>-->
					<!--          <Button class="mr10" @click="getExpressList">下载物流公司对照表</Button>-->
				</div>
			</div>
			<vxe-table bstock="inner" ref="xTable" class="mt25" :loading="loading" row-id="id"
				:expand-config="{accordion: true}" :checkbox-config="{reserve: true}" @checkbox-all="checkboxAll"
				@checkbox-change="checkboxItem" :data="stockList" v-if="tabType != 1">
				<vxe-column field="oms_sku" :title="$t('page.product.SKU')" min-width="330" align="left"
					fixed="left"></vxe-column>
				<vxe-column field="warehouse_id" :title="$t('page.stock.stock_name')" min-width="120" align="left"
					fixed="left">
					<template v-slot="{ row }">
						<div slot="content">
							<span v-if="row.warehouse_id == '1791498718751334401'">CA 5005</span>
							<span v-if="row.warehouse_id == '101816795504'">Houston</span>
						</div>
					</template>
				</vxe-column>
				<vxe-column field="available_quantity" :title="$t('page.stock.available')" min-width="120" align="left"
					fixed="left"></vxe-column>

				<vxe-column field="sku_name_en" :title="$t('page.stock.item_name')" min-width="330"></vxe-column>
				<vxe-column field="standard_quantity" :title="$t('page.stock.std_qoh')" min-width="120"></vxe-column>
				<vxe-column field="broken_quantity" :title="$t('page.stock.dmg_qoh')" min-width="150"></vxe-column>
				<vxe-column field="inbounding_quantity" :title="$t('page.stock.inbounding')"
					min-width="120"></vxe-column>
				<vxe-column field="outbounding_quantity" :title="$t('page.stock.outbounding')"
					min-width="130"></vxe-column>
			</vxe-table>
			<vxe-table bstock="inner" ref="xTable" class="mt25" :loading="loading" row-id="id"
				:expand-config="{accordion: true}" :checkbox-config="{reserve: true}" @checkbox-all="checkboxAll"
				@checkbox-change="checkboxItem" :data="stockHistoryList" v-else>
				<vxe-column :title="$t('page.stock.timestamp')" min-width="190" field="create_time"
					:formatter="formatDateColumn"></vxe-column>
				<vxe-column field="oms_sku" title="" min-width="5"></vxe-column>
				<vxe-column field="oms_sku" :title="$t('page.product.SKU')" min-width="190"></vxe-column>
				<vxe-column field="warehouse_name" :title="$t('page.stock.warehouse')" min-width="190"></vxe-column>
				<vxe-column field="quantity_change" :title="$t('page.stock.qty_change')" min-width="90"></vxe-column>
				<vxe-column field="ava_quantity" :title="$t('page.stock.qoH')" min-width="90"></vxe-column>
				<vxe-column field="type" :title="$t('page.stock.type')" min-width="90"></vxe-column>
				<vxe-column field="remark_cn" :title="$t('page.stock.change_activity')" min-width="190"></vxe-column>


			</vxe-table>
			<div class="acea-row row-right mt15">
				<Page :total="total" :current="stockData.page" @on-change="pageChange" :page-size="stockData.limit" />
			</div>
		</Card>
	</div>
</template>

<script>
	import {
		mapState
	} from "vuex";
	import editFrom from "@/components/from/from";
	import {
		getNoPageSupplierProductList
	} from "@/api/supplier";
	// import userDetails from "@/components/userDetails/userDetails";
	import Setting from "@/setting";
	import {
		stockList,
		exportStockList,
		stockHistoryList,
		exportStockHistoryList
	} from "@api/stock";
	export default {
		name: "index",
		components: {
			editFrom,
			// userDetails,
		},
		data() {
			return {
				isAll: 0,
				stockNameList: [{
					value: '1791498718751334401',
					label: 'CA5005'
				}, {
					value: '101816795504',
					label: 'Houston'
				}],
				supplierList: [],
				isCheckBox: false,
				timeVal: "",
				checkUidList: [],
				// 订单列表
				stockData: {
					page: 1,
					limit: 10,
					type: "",
					status: "",
					data: "",
					real_name: "",
					warehouse_name: "",
					code:"",
					supplier_id: "",
					sku: "",
					pay_type: "",
					stock_type: "0",
					field_key: "all",
					tab_type: 0,
				},
				stockList: [],
				stockHistoryList: [],
				total: 0,
				loading: false,
				tabType: 0,
			};
		},
		watch: {
			$route() {
				if (this.$route.fullPath === `${Setting.roterPre}/stock/list?type=7&status=1`) {
					this.getPath();
				}
			}
		},
		computed: {
			...mapState("store/layout", ["isMobile"]),
			labelWidth() {
				return this.isMobile ? undefined : 80;
			},
			labelPosition() {
				return this.isMobile ? "top" : "right";
			},
			stockSkuList() {
				return [{
					value: '0',
					label: $t('page.stock.all_sku')
				}, {
					value: '1',
					label: $t('page.stock.in_stock')
				}, {
					value: '3',
					label: $t('page.stock.show_low_sku')
				}, {
					value: '4',
					label: $t('page.stock.zero_sku')
				}]
			}
		},
		created() {
			if (this.$route.fullPath === `${Setting.roterPre}/stock/list?type=7&status=1`) {
				this.getPath();
			} else {
				this.getList();
			}
		},
		mounted() {
			this.getSupplierList();
		},
		methods: {

			//获取供应商列表；
			getSupplierList() {
				getNoPageSupplierProductList()
					.then(async (res) => {
						this.supplierList = res.data.info;
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			// 具体日期
			onchangeTime(e) {
				if (e[1].slice(-8) === "00:00:00") {
					e[1] = e[1].slice(0, -8) + "23:59:59";
					this.timeVal = e;
				} else {
					this.timeVal = e;
				}
				this.stockData.data = this.timeVal[0] ? this.timeVal.join("-") : "";
				this.stockData.page = 1;
				this.allReset();
				this.getHistoryList();
			},
			reset() {
				this.timeVal = ""
				this.stockData = {
					page: 1,
					limit: 10,
					type: "",
					status: "",
					data: "",
					real_name: "",
					warehouse_name: "",
					code:"",
					sku: "",
					pay_type: "",
					stock_type: "0",
					field_key: "all",
					tab_type: 0,
				};
				this.onClickTab(0)
				// this.getList(this.ids);
			},
			// 列格式化函数
			formatDateColumn({
				cellValue
			}) {
				const date = new Date(cellValue);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},
			//切换头部列表
			onClickTab(e) {
				this.tabType = e
				if (e != 1) {
					this.allReset();
					this.stockData.tab_type = e;
					this.stockData.page = 1;
					this.getList();
				} else {
					//历史库存列表
					this.allReset();
					this.stockData.tab_type = e;
					this.stockData.page = 1;
					this.getHistoryList();
				}

			},
			//跳转刷新
			getPath() {
				this.stockData.page = 1;
				this.stockData.status = this.$route.query.status;
				this.getList();
			},
			allReset() {
				this.isAll = 0;
				// this.stockData.sku = "";
				// this.stockData.data = "";
				this.isCheckBox = false;
				this.$refs.xTable.setAllCheckboxRow(false);
				this.checkUidList = [];
			},
			checkboxItem(e) {
				let id = parseInt(e.rowid);
				let index = this.checkUidList.indexOf(id);
				if (index !== -1) {
					this.checkUidList = this.checkUidList.filter((item) => item !== id);
				} else {
					this.checkUidList.push(id);
				}
			},
			checkboxAll() {
				// 获取选中当前值
				let obj2 = this.$refs.xTable.getCheckboxRecords(true);
				// 获取之前选中值
				let obj = this.$refs.xTable.getCheckboxReserveRecords(true);
				if (this.isAll == 0 && this.checkUidList.length <= obj.length && !this.isCheckBox) {
					obj = [];
				}
				obj = obj.concat(obj2);
				let ids = [];
				obj.forEach((item) => {
					ids.push(parseInt(item.id))
				})
				this.checkUidList = ids;
				if (!obj2.length) {
					this.isCheckBox = false;
				}
			},

			getHistoryList() {
				this.loading = true;
				stockHistoryList(this.stockData).then(res => {
					let data = res.data;
					this.$set(this, 'stockHistoryList', data.list);
					this.total = res.data.count;
					this.loading = false;
				}).catch(err => {
					this.loading = false;
					this.$Message.error(err.msg)
				})
			},
			getList() {
				this.loading = true;
				stockList(this.stockData).then(res => {
					let data = res.data;
					this.$set(this, 'stockList', data.list);
					this.total = res.data.count;
					this.loading = false;
				}).catch(err => {
					this.loading = false;
					this.$Message.error(err.msg)
				})
			},
			pageChange(index) {
				this.stockData.page = index;
				if (this.tabType != 1) {
					//库存列表
					this.getList();
				} else {
					//历史库存列表
					this.getHistoryList();
				}
			},
			userSearchs() {
				this.allReset();
				if (this.tabType != 1) {
					this.stockData.page = 1;
					this.getList();
				} else {
					this.stockData.page = 1;
					this.getHistoryList();
				}

			},
			async exportStock() {
				try {
					this.exportLoading = true;
					let res; // 在函数作用域声明
					// 1. 调用导出接口获取文件信息
					if (this.tabType != 1) {
						res = await exportStockList(this.stockData);
					} else {
						res = await exportStockHistoryList(this.stockData);
						console.log("res111---------", res);
					}
					// const res = await exportStockHistoryList(this.stockData);
					// 2. 检查响应是否成功
					if (res.code !== 0) {
						throw new Error(res.msg || '导出失败');
					}

					// 3. 获取文件信息
					const fileInfo = res.data;

					// 4. 使用文件URL下载文件
					await this.downloadFile(fileInfo);

					// 5. 显示成功消息
					Message.success('导出成功，文件已开始下载');

				} catch (error) {
					// 错误处理
					Message.error(error.message || '导出失败，请重试');
					console.error('导出错误:', error);
				} finally {
					this.exportLoading = false;
				}
			},
			async downloadFile(fileInfo) {
				try {
					// 1. 创建下载链接（优先使用 download_url，再使用 exports_url）
					// const downloadUrl = fileInfo.download_url || fileInfo.exports_url;
					const downloadUrl = fileInfo.exports_url;
					// 2. 创建隐藏的<a>标签触发下载
					const link = document.createElement('a');
					link.href = downloadUrl;

					// 从URL中提取文件名，或自定义文件名
					const fileName = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
					link.download = fileName; // 设置下载文件名

					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);

				} catch (error) {
					console.error('文件下载错误:', error);
					throw new Error('文件下载失败: ' + error.message);
				}
			},
			getFullUrl(url) {
				// 如果已经是完整URL，直接返回
				if (url.startsWith('http://') || url.startsWith('https://')) {
					return url;
				}

				// 处理Windows路径分隔符问题
				const cleanUrl = url.replace(/\\/g, '/');

				// 如果是绝对路径，直接返回（根据当前域名）
				if (cleanUrl.startsWith('/')) {
					return `${window.location.origin}${cleanUrl}`;
				}

				// 相对路径处理（基于当前页面）
				return `${window.location.origin}${window.location.pathname}/../${cleanUrl}`;
			}
		},
	};
</script>

<style lang="stylus" scoped>
	.tdinfo {
		margin-left: 75px;
		margin-top: 16px;
	}

	.expand-row {
		margin-bottom: 16px;
		font-size: 12px;
	}

	.tabBox {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;

		.tabBox_img {
			width: 30px;
			height: 30px;

			img {
				width: 100%;
				height: 100%;
			}
		}

		.tabBox_tit {
			width: 267px;
			height: 30px;
			line-height: 30px;
			font-size: 12px !important;
			margin: 0 2px 0 10px;
			letter-spacing: 1px;
			box-sizing: bstock-box;
		}
	}

	.tabBox+.tabBox {
		margin-top: 5px;
	}
</style>